﻿using DataCapture.Helper;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Threading;
using static DataCapture.Helper.PublicHelp;

namespace DataCapture.DeviceDataSave;

public class DeviceJXS: DeviceBase

{
    
    private DeviceData<JXS_PLC_ActionDataModel> deviceData;
    private Func<Func<string, int>, JXS_PLC_ActionDataModel> mapper;
    public DeviceJXS(string plcName, ElementConfig elementConfig, CancellationToken cancellationToken) : base(plcName, elementConfig)
    {
        deviceData = new DeviceData<JXS_PLC_ActionDataModel>();
        this.plcName = plcName;//plc名称
        List<PlcPart> plcParts = new List<PlcPart>();
        foreach (var moduleConfig in elementConfig.ModuleConfig)
        {
            if (moduleConfig.PartList == null || moduleConfig.PartList.Count < 0)
            {
                continue;
            }
            plcParts.AddRange(moduleConfig.PartList);
        }
        mapper = MapperCache.GetMapper<JXS_PLC_ActionDataModel>(_cachedDelegates, plcParts.ToArray());

        Task.Run(() =>
        {
            ReadActionData(cancellationToken, () =>
            {
                if (mapper == null)
                {
                    return;
                }
                //数据缓存获取PLC数据
                Func<string, int> getData = GetData;

                // 4. 执行映射，生成实体对象
                var result = mapper(getData);
                deviceData.timeStamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                deviceData.deviceId = elementConfig.DeviceId;
                deviceData.dataType = "Action";
                deviceData.data = result;

                //转发数据
                MQTTConsoleServer.Instance.ForwardData(deviceData, topic);
            });

        }, cancellationToken);
        Log4NetHelper.Debug($"【机械手机{elementConfig.DeviceId}】数据采集已经启动", true);
    }
}